/*
 * @Author: tanjunyi@doctorwork.com
 * @Date: 2020-07-21 21:58:09
 * @LastEditors: tanjunyi@doctorwork.com
 * @LastEditTime: 2020-07-27 18:02:18
 * @Description:
 */

// 初始化vue.use功能
let Vue;
const install = _Vue => {
	if (Vue != _Vue) {
		Vue = _Vue
	}
	Vue.mixin({
		beforeCreate() {
			if (this.$options && this.$options.store) {
				this.$store = this.$options.store
			} else {
				this.$store = this.$parent && this.$parent.$store
			}
		},
	})
}
// 初始化Store相关功能

class Store {
	constructor(options) {
		// 这里的响应式数据处理
		this.globalState = new Vue({
			data() {
				return {
					state: options.state
				}
			}
		})
		// 处理getters
		this.getters = {};
		Object.keys(options.getters).forEach(key => {
			Object.defineProperty(this.getters, key, {
				get: () => {
					return options.getters[key](this.state)
				}
			})
		})
		// 处理mutations
		this.mutations = {};
		Object.keys(options.mutations).forEach(key => {
			this.mutations[key] = payload => {
				options.mutations[key](this.state, payload)
			}
		})
		// 处理actions 
		this.actions = {};
		Object.keys(options.actions).forEach(key => {
			this.actions[key] = payload => {
				options.actions[key](this, payload)
			}
		})
		// 处理commit
		this.commit = (key, payload) => {
			this.mutations[key](payload)
		}
		// 处理dispatch
		this.dispatch = (key, payload) => {
			this.actions[key](payload)
		}
	}

	get state() {
		return this.globalState.state
	}
}

export const mapState = function (obj) {
	let result = {}
	return result;
}

export default {
	install,
	mapState,
	Store
};